package com.open.capacity.salary.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.open.capacity.commons.Result;
import com.open.capacity.model.system.LoginAppUser;
import com.open.capacity.model.system.SysUser;
import com.open.capacity.reimburse.util.uuid.UUIDUtils;
import com.open.capacity.salary.dto.RecordTaxExcelModel;
import com.open.capacity.salary.entity.GzItem;
import com.open.capacity.salary.entity.GzRecordSalary;
import com.open.capacity.salary.service.GzEnableMonthService;
import com.open.capacity.user.excel.UserExcel;
import com.open.capacity.user.model.SysCompany;
import com.open.capacity.user.model.SysDepartment;
import com.open.capacity.user.service.SysDepartmentService;
import com.open.capacity.user.service.SysUserService;
import com.open.capacity.utils.StringUtil;
import com.open.capacity.utils.SysUserUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.open.capacity.commons.PageResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.open.capacity.commons.CodeEnum;

import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import org.apache.commons.collections4.MapUtils;

import com.open.capacity.salary.entity.GzRecordTax;
import com.open.capacity.salary.dao.GzRecordTaxDao;
import com.open.capacity.salary.service.GzRecordTaxService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;

@Slf4j
@Service
public class GzRecordTaxServiceImpl implements GzRecordTaxService {

    @Autowired
    private GzRecordTaxDao gzRecordTaxDao;

    @Autowired
    private GzEnableMonthService gzEnableMonthService;

    @Autowired
    private SysDepartmentService departmentService;

    @Autowired
    private SysUserService userService;

    /**
     * 添加
     *
     * @param gzRecordTax
     */
    public int save(GzRecordTax gzRecordTax) {
        gzRecordTax.setId(UUIDUtils.getOriginalUUIDWithoutBar());
        gzRecordTax.setStatus(1);
        gzRecordTax.setUpdateTime(new Date());
        return gzRecordTaxDao.save(gzRecordTax);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int batchSave(String companyId, String ztId, List<GzRecordTax> list) {
        LoginAppUser loginUser = SysUserUtil.getLoginAppUser();
        //机构当前月份
        String currentMonth = gzEnableMonthService.findByZtId(companyId, ztId).getCurrentMonth();

        gzRecordTaxDao.deleteByZtId(companyId, ztId, currentMonth);

        for (GzRecordTax item : list) {
            item.setId(UUIDUtils.getOriginalUUIDWithoutBar());
            item.setStatus(1);
            item.setCompanyId(companyId);
            item.setZtId(ztId);
            item.setMonth(currentMonth);
            item.setUpdateUserid(loginUser.getId());
            item.setUpdateTime(new Date());
            item.setUpdateUsername(loginUser.getRealName());
            gzRecordTaxDao.save(item);
        }
        return list.size();
    }

    /**
     * 修改
     *
     * @param gzRecordTax
     */
    public int update(GzRecordTax gzRecordTax) {
        gzRecordTax.setUpdateTime(new Date());
        return gzRecordTaxDao.update(gzRecordTax);
    }


    /**
     * 删除
     *
     * @param id
     */
    public int delete(String id) {
        return gzRecordTaxDao.delete(id);
    }

    /**
     * 查询记录
     *
     * @param id
     * @return
     */
    public GzRecordTax findById(String id) {
        return gzRecordTaxDao.findById(id);
    }

    @Override
    public GzRecordTax findByUserId(String companyId, String ztId, String userId, String month) {
        return gzRecordTaxDao.findByUserId(companyId, ztId, userId, month);
    }

    /**
     * 分页
     *
     * @param params
     * @return
     */
    public PageResult<GzRecordTax> pageAll(Map<String, Object> params) {
        String companyId = params.get("companyId").toString();
        String ztId = params.get("ztId").toString();
        //机构当前月份
        String currentMonth = gzEnableMonthService.findByZtId(companyId, ztId).getCurrentMonth();
        params.put("month", currentMonth);

        //设置分页信息，分别是当前页数和每页显示的总记录数【记住：必须在mapper接口中的方法执行之前设置该分页信息】
        if (MapUtils.getInteger(params, "page") != null && MapUtils.getInteger(params, "limit") != null)
            PageHelper.startPage(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit"), true);


        List<GzRecordTax> list = gzRecordTaxDao.findAll(params);
        PageInfo<GzRecordTax> pageInfo = new PageInfo(list);

        return PageResult.<GzRecordTax>builder().data(pageInfo.getList()).resp_code(CodeEnum.SUCCESS.getCode()).count(pageInfo.getTotal()).build();
    }

    /**
     * 列表
     *
     * @param params
     * @return
     */
    public List<GzRecordTax> findAll(Map<String, Object> params) {
        String companyId = params.get("companyId").toString();
        String ztId = params.get("ztId").toString();
        //机构当前月份
        String currentMonth = gzEnableMonthService.findByZtId(companyId, ztId).getCurrentMonth();
        params.put("month", currentMonth);
        return gzRecordTaxDao.findAll(params);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int importExcel(String companyId, String ztId, MultipartFile multipartFile) throws Exception {
        LoginAppUser loginUser = SysUserUtil.getLoginAppUser();
        ImportParams params = new ImportParams();
        params.setHeadRows(1);
        // params.setTitleRows(0);
        // 开启excel校验
        params.setNeedVerify(true);

        //根据名称查部门用户id缓存map
        Map<String, SysDepartment> departmentCacheMap = new HashMap<>();
        Map<String, SysUser> userCacheMap = new HashMap<>();

        ExcelImportResult<RecordTaxExcelModel> result = new ExcelImportResult();
        try {
            result = ExcelImportUtil.importExcelMore(multipartFile.getInputStream(),
                    RecordTaxExcelModel.class, params);
        } catch (Exception e) {
            log.error(e.toString());
            log.error("从文件读取数据错误:{}", e.getMessage());
        }
        if (result.isVerifyFail()) {
            StringBuilder temp = new StringBuilder();
            for (RecordTaxExcelModel entity : result.getFailList()) {
                temp.append("第").append(entity.getRowNum()).append("行的错误是：").append(entity.getErrorMsg());
            }
            throw new Exception("Excel文件校验不通过:" + temp.toString());
        }

        String errMsg = "";// valid(result.getList(), true);
        List<GzRecordTax> data = new ArrayList<>();
        if (StringUtil.isEmpty(errMsg)) {
            for (RecordTaxExcelModel item : result.getList()) {
                GzRecordTax model = new GzRecordTax();
                BeanUtils.copyProperties(item, model);
                model.setUserName(item.getUserName());

                model.setCompanyId(companyId);
                model.setZtId(ztId);
                model.setCategory("1");

                SysDepartment department = departmentCacheMap.get(item.getDepartmentName()) != null ? departmentCacheMap.get(item.getDepartmentName()) : departmentService.findByName(companyId, item.getDepartmentName());
                Assert.notNull(department, "找不到部门：" + item.getDepartmentName());
                departmentCacheMap.put(item.getDepartmentName(), department);
                model.setDepartmentId(department.getId());
                SysUser user = userCacheMap.get(item.getDepartmentName() + item.getUserName()) != null ? userCacheMap.get(item.getDepartmentName() + item.getUserName()) : userService.findByName(companyId, department.getId(), item.getUserName());
                Assert.notNull(user, "找不到员工：" + item.getDepartmentName() + " " + item.getUserName());
                userCacheMap.put(item.getDepartmentName() + item.getUserName(), user);
                model.setUserId(user.getId());

                data.add(model);
            }
            //执行写入
            // batchSave(companyId, ztId, data);

            //机构当前月份
            String currentMonth = gzEnableMonthService.findByZtId(companyId, ztId).getCurrentMonth();

            for (GzRecordTax item : data) {
                GzRecordTax model = gzRecordTaxDao.findByUserId(companyId, ztId, item.getUserId(), currentMonth);
                if (model == null) {
                    item.setId(UUIDUtils.getOriginalUUIDWithoutBar());
                    item.setStatus(1);
                    item.setCompanyId(companyId);
                    item.setZtId(ztId);
                    item.setUserId(item.getUserId());
                    item.setMonth(currentMonth);
                    item.setUpdateUserid(loginUser.getId());
                    item.setUpdateTime(new Date());
                    item.setUpdateUsername(loginUser.getRealName());
                    gzRecordTaxDao.save(item);
                } else {
                    item.setId(model.getId());
                    item.setStatus(1);
                    item.setUpdateUserid(loginUser.getId());
                    item.setUpdateTime(new Date());
                    item.setUpdateUsername(loginUser.getRealName());
                    gzRecordTaxDao.update(item);
                }
            }

            return result.getList().size();
        } else {
            throw new Exception(errMsg);
        }
    }
}
